package kr.saeildamil.androidforstudy2.ch31;

import kr.saeildamil.androidforstudy2.R;
import android.app.Activity;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.TextView;

public class PinchZoom extends Activity {
	
	final static float STEP = 200;
	TextView mTextRatio;
	float mRatio = 1.0f;
	int mBaseDistance;
	float mBaseRatio;
	ImageView mImage;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch31_pinchzoom);
		
		mTextRatio = (TextView) findViewById(R.id.ratio);
		mTextRatio.setText(Float.toString(mRatio));
		
		mImage = (ImageView) findViewById(R.id.image);
		
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getPointerCount()==2){
			int action = event.getAction();
			int pureaction = action & MotionEvent.ACTION_MASK;
			
			if(pureaction == MotionEvent.ACTION_POINTER_DOWN){
				mBaseDistance = getDistance(event);
				mBaseRatio = mRatio;
			}else{
				float delta = (getDistance(event) - mBaseDistance)/STEP;
				float multi = (float) Math.pow(2, delta);
				mRatio = Math.min(1024f, Math.max(0.1f, mBaseRatio * multi));
				mTextRatio.setText(String.format("%.2f", mRatio));
				
				Matrix matrix = new Matrix();
				matrix.postScale(mRatio, mRatio);
				mImage.setImageMatrix(matrix);
			}
		}
		return super.onTouchEvent(event);
	}
	
	int getDistance(MotionEvent event){
		int dx = (int)(event.getX(0) - event.getX(1));
		int dy = (int)(event.getY(0) - event.getY(1));
		int distance = (int)(Math.sqrt(dx*dx + dy*dy));
		return (int)(Math.sqrt(dx*dx + dy*dy));
		
	}
}
